package com.example.skillcinema.ui.screens.main.viewmodels

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.PagingData
import androidx.paging.cachedIn
import com.example.skillcinema.adapters.GalleryPagingSource
import com.example.skillcinema.db.enums.GalleryImageTypes
import com.example.skillcinema.db.repositories.BaseRepository.Companion.PREVIEW_ITEMS_COUNT
import com.example.skillcinema.db.repositories.FilmRepository
import com.example.skillcinema.db.responses.ImageItemResponse
import dagger.hilt.android.lifecycle.HiltViewModel
import jakarta.inject.Inject
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.launch

@HiltViewModel
class GalleryListViewModel @Inject constructor(val repository: FilmRepository) : ViewModel() {
    private val _imageTypesStateFlow: MutableStateFlow<List<GalleryImageTypes>> =
        MutableStateFlow(listOf())
    val imageTypes = _imageTypesStateFlow.asStateFlow()
    private val _currentImageType: MutableStateFlow<GalleryImageTypes> =
        MutableStateFlow(GalleryImageTypes.STILL)

    val imagesPaged: Flow<PagingData<ImageItemResponse>> =
        _currentImageType.flatMapLatest { imageType ->
                Pager(
                    config = PagingConfig(PREVIEW_ITEMS_COUNT),
                    pagingSourceFactory = {
                        GalleryPagingSource { page ->
                            getData(
                                page,
                                imageType
                            )
                        }
                    }).flow.cachedIn(viewModelScope)
            }
    private var id: Int = 0
    private suspend fun getData(page: Int, type: GalleryImageTypes): List<ImageItemResponse> {
        return repository.getGalleryImageByType(id, page, type)
    }

    fun setId(newId: Int) {
        id = newId
    }

    fun loadData() {
        viewModelScope.launch {
            _imageTypesStateFlow.value = repository.getNotEmptyGalleryTypes(id)
        }
    }

    fun setImageType(type: GalleryImageTypes) {
        _currentImageType.value = type
    }
}